package com.qf.qfbehavior.controller.v1;

import com.qf.qfleadnewscommons.mvc.ThreadLocalUtils;
import com.qf.qfleadnewsmodel.behavior.dtos.BehaviorDto;
import com.qf.qfleadnewsmodel.commons.consts.RedisConst;
import com.qf.qfleadnewsmodel.commons.dtos.ResponseResult;
import com.qf.qfleadnewsmodel.enums.AppHttpCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/v1")
public class BehaviorController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 对文章的阅读行为
     * @param behaviorDto
     * @return
     */
    @PostMapping("/read_behavior")
    public ResponseResult read(@RequestBody BehaviorDto behaviorDto){

        redisTemplate.opsForValue().increment(RedisConst.ARTICLE_READ_PREFIX + behaviorDto.getArticleId());

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 对文章的店点赞行为
     * @param behaviorDto
     * @return
     */
    @PostMapping("/likes_behavior")
    public ResponseResult like(@RequestBody BehaviorDto behaviorDto){

        String key = RedisConst.ARTICLE_LIKE_PREFIX + behaviorDto.getArticleId();
        long offset = ThreadLocalUtils.getUid();
        redisTemplate.opsForValue().setBit(key,offset,behaviorDto.getOperation()==0);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 对文章的不喜欢行为
     * @param behaviorDto
     * @return
     */
    @PostMapping("/un_likes_behavior")
    public ResponseResult unlike(@RequestBody BehaviorDto behaviorDto){

        String key = RedisConst.ARTICLE_UNLIKE_PREFIX + behaviorDto.getArticleId();
        long offset = ThreadLocalUtils.getUid();
        redisTemplate.opsForValue().setBit(key,offset,behaviorDto.getType() == 0);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
